package cn.glenn._03vehicle.controller;

import cn.glenn._03vehicle.base.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) {
        //获取原始文件名：image.png
        String filename = file.getOriginalFilename();
        //获取文件名后缀
        String suffix = filename != null ? filename.substring(filename.lastIndexOf(".")) : null;
        //生成全球唯一文件名
        filename = UUID.randomUUID() + suffix;
        //生成日期路径
        SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = dateFormat.format(new Date());
        //创建对应目录
        String dirPath = "d:/files";
        File file1 = new File(dirPath + datePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //保存文件到服务器
        String filePath = dirPath + datePath + filename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }
        log.info("filename:{}", filename);
        return JsonResult.success(datePath + filename);
    }
}
